package test.gps;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.format.Time;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
	private TabHost tabHost;
	private LocationListener locListenD;
	public TextView etLatitude;
	public TextView etLongitude;
	public TextView etAccuracy;
	public TextView etSpeed;
	public TextView etAltitude;
	public TextView seeSatellites;
	public TextView useSatellites;
	public EditText etNmea0183;
	public ImageView imageViewdb;
	public ToggleButton recordNMEA;
	public Button check;
	private FileHelper helper;
	private String folderName = null;
	float x = 0;
	float y = 0;
	String isOK = "V";
	private SharedPreferences sp;
	private SatellitesView satellitesView;
	String UTCdate = "";
	String UTCtime = "";
	String gpsData = "";
	String NMEANAME = "NMEA实时数据.txt";
	String SATELLITESDATA = "卫星状态数据.txt";
	String GPSDATA = "实时定位数据.txt";
	int rtime=0;
	int sttime=0;
	private class MyNmeaListener implements GpsStatus.NmeaListener {
		@Override
		public void onNmeaReceived(long timestamp, String nmea) {
			// Toast.makeText(MainActivity.this, nmea + " ",
			// Toast.LENGTH_SHORT).show();
			if (folderName != null) {
				helper.writeSDFile(nmea, folderName, NMEANAME);
			}
			Editable e = etNmea0183.getText();
			int len = e.length();
			// if (len > 5000) {
			// e.delete(0, 2500);
			// }

			e.append(nmea);

			len = e.length();
			etNmea0183.setSelection(len - 1, len - 1);
			System.out.println("Nmea0183" + nmea);

			if (nmea.startsWith("$GPGSV")) {
				String tokens[] = nmea.split(",");
				// useSatellites.setText(tokens[3]);
				for (int i = 0; i < 4 && (4 * i + 6) < tokens.length; i++) {
					if (folderName != null) {
						String data = "";
						for (int j = 4; j < 8; j++) {
							if (4 * i + j + 1 == tokens.length) {
								String[] a = tokens[4 * i + j].split("\\*");
								tokens[4 * i + j] = a[0];
							}
							if (tokens[4 * i + j].equals("")) {
								data += "0";
							} else {
								data += tokens[4 * i + j];
							}
							if (j != 7) {
								data += ",";
							} else {
								data += "\n";
							}
						}

						helper.writeSDFile(data, folderName, SATELLITESDATA);
					}
				}
			}

			if (nmea.startsWith("$GPGGA")) {
				String tokens[] = nmea.split(",");
				if (tokens[7].equals("")) {
					tokens[7] = "0";
				} else if (isOK.equals("A")) {
					etLatitude.setText(tokens[3] + ((int)(Float.valueOf(tokens[2])
							/ 100)+(100*(Float.valueOf(tokens[2])/100.0-(int)(Float.valueOf(tokens[2])/ 100))/60.0)));
					etLongitude.setText(tokens[5] + ((int)(Float.valueOf(tokens[4])
							/ 100)+(100*(Float.valueOf(tokens[4])/100.0-(int)(Float.valueOf(tokens[4])/ 100))/60.0)));
				}
				useSatellites.setText("正在使用:"+Integer.parseInt(tokens[7]));

				gpsData = tokens[7] + "," + tokens[2] + "," + tokens[3] + ","
						+ tokens[4] + "," + tokens[5] + "," + tokens[8] + ","
						+ tokens[9];

			}
			if (nmea.startsWith("$GPRMC")) {
				String tokens[] = nmea.split(",");
				if (tokens[2].equals("A")) {
					isOK = "A";
					UTCdate = tokens[9];
					UTCtime = tokens[1];
				} else {
					isOK = "V";
				}
				if (folderName != null) {
				helper.writeSDFile(
						isOK + "," + UTCdate + "," + UTCtime + "#\n",
						folderName, SATELLITESDATA);
				helper.writeSDFile(isOK + "," + UTCdate + "," + UTCtime + ","
						+ gpsData + "\n", folderName, GPSDATA);
				gpsData = "";
				UTCdate = "";
				UTCtime = "";
				}
			}
			if(rtime!=0){
			Time t = new Time();
			t.setToNow(); // 取得系统时间
			if((t.minute+60-sttime)%60>=rtime&&folderName!=null){
				folderName = null;
				Toast.makeText(MainActivity.this,
						"定时时间到，停止记录NMEA数据，数据已存储在SD卡GPS文件夹中",
						Toast.LENGTH_SHORT).show();
				recordNMEA.setChecked(false);
			}
			}

		}
	};

	private class MyGpsStatusListener implements GpsStatus.Listener {
		@Override
		public void onGpsStatusChanged(int event) {

			GpsStatus gpsStatus = ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
					.getGpsStatus(null);
			if (event == GpsStatus.GPS_EVENT_FIRST_FIX) {

			} else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {

				Iterable<GpsSatellite> iterable = gpsStatus.getSatellites();
				Iterator<GpsSatellite> itrator = iterable.iterator();
//				listItem.clear();
//				Satelliteslist.setDividerHeight(0);

				ArrayList<GpsSatellite> satelliteList = new ArrayList<GpsSatellite>();
				int count = 0;
				int maxSatellites = gpsStatus.getMaxSatellites();
				while (itrator.hasNext() && count <= maxSatellites) {
					GpsSatellite itrator1 =itrator.next();
					if(itrator1.getPrn()<33){
					count++;
					satelliteList.add(itrator1);
					
					}
				}
				seeSatellites.setText("可见卫星数:" + count);
				if(satellitesView!=null)
				satellitesView.repaintSatellites(satelliteList);
//				for (int i = 0; i < satelliteList.size(); i++) {
//					HashMap<String, Object> map = new HashMap<String, Object>();
//					map.put("getAzimuth", satelliteList.get(i).getAzimuth());
//					map.put("getElevation", satelliteList.get(i).getElevation());
//					map.put("num",
//							String.valueOf(satelliteList.get(i).getPrn()));
//					map.put("getSnr", satelliteList.get(i).getSnr());
//					map.put("size", (int) satelliteList.get(i).getSnr());
////					listItem.add(map);
//
//				}

			} else if (event == GpsStatus.GPS_EVENT_STARTED) {

			} else if (event == GpsStatus.GPS_EVENT_STOPPED) {
			}
		}
	};

	private class MyLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location location) {
			if (isOK.equals("V")) {
				etLatitude.setText(Double.toString(location.getLatitude()));
				etLongitude.setText(Double.toString(location.getLongitude()));
			}
			etAccuracy.setText(Float.toString(location.getAccuracy()));
			etSpeed.setText(Float.toString(location.getSpeed()));
			etAltitude.setText(Double.toString(location.getAltitude()));

		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(MainActivity.this, provider + " 不可用",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(MainActivity.this, provider + " 可用",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			switch (status) {
			case GpsStatus.GPS_EVENT_STARTED:
				Toast.makeText(MainActivity.this, "GPS_EVENT_STARTED",
						Toast.LENGTH_SHORT).show();
				break;

			case GpsStatus.GPS_EVENT_STOPPED:
				Toast.makeText(MainActivity.this, "GPS_EVENT_STOPPED",
						Toast.LENGTH_SHORT).show();
				break;

			case GpsStatus.GPS_EVENT_FIRST_FIX:
				Toast.makeText(MainActivity.this, "GPS_EVENT_FIRST_FIX",
						Toast.LENGTH_SHORT).show();
				break;

			case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
				Toast.makeText(MainActivity.this, "GPS_EVENT_SATELLITE_STATUS",
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置无标题栏
		setContentView(R.layout.main);

		tabHost = (TabHost) findViewById(R.id.customer_tabhost);
		tabHost.setup(); // 记得要用setup()方法来初始化TabHost

		tabHost.addTab(tabHost.newTabSpec("tab_1").setIndicator("实时定位数据")
				.setContent(R.id.tab_1));
		tabHost.addTab(tabHost.newTabSpec("tab_2").setIndicator("NMEA数据")
				.setContent(R.id.tab_2));
		etLatitude = (TextView) findViewById(R.id.textViewLatitude);
		etLongitude = (TextView) findViewById(R.id.textViewLongitude);
		etAccuracy = (TextView) findViewById(R.id.textViewAccuracy);
		etSpeed = (TextView) findViewById(R.id.textViewSpeed);
		etAltitude = (TextView) findViewById(R.id.textViewAltitude);
		useSatellites = (TextView) findViewById(R.id.textViewuse);
		seeSatellites = (TextView) findViewById(R.id.textViewsee);
		etNmea0183 = (EditText) findViewById(R.id.etNmea0183);
		satellitesView = (SatellitesView) findViewById(R.id.satellitesView);
		recordNMEA = (ToggleButton) findViewById(R.id.record);
		helper = new FileHelper(getApplicationContext());
		sp = this.getSharedPreferences("flag", Context.MODE_WORLD_READABLE);
		
		check = (Button) findViewById(R.id.checkdata);
		check.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, DataListActivity.class);
				startActivity(intent);
			}
		});
		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			etLatitude.setText("DISABLED GPS");
			etLongitude.setText("DISABLED GPS");
			Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
		}
		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
			Toast.makeText(this, "GPS已开启", Toast.LENGTH_SHORT).show();
		Location ll = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (ll != null) {
			etLatitude.setText(Double.toString(ll.getLatitude()));
			etLongitude.setText(Double.toString(ll.getLongitude()));
		}

		MyNmeaListener nmeaListen = new MyNmeaListener();
		lm.addNmeaListener(nmeaListen);

		MyGpsStatusListener gpsStatusListener = new MyGpsStatusListener();
		lm.addGpsStatusListener(gpsStatusListener);

		locListenD = new MyLocationListener();
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0,
				locListenD);

		// 初始化设置一次标签背景
		updateTabStyle(tabHost);

		// 当某个Tab被选中时，则更新背景样式
		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				updateTabStyle(tabHost);
			}
		});
		// Add Click Listeners to Buttons
		recordNMEA.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if (recordNMEA.isChecked()) {
					if (helper.hasSD()) {
						Time t = new Time();
						t.setToNow(); // 取得系统时间。
						folderName = t.format2445();
						try {
							helper.createSDFile(folderName);
						
						
						 rtime = sp.getInt("RTIME", 0);
						if(rtime!=0){
							sttime = t.minute;
							
							Toast.makeText(
									MainActivity.this,
									"您将记录" + rtime
											+ "分钟的NMEA数据将存储在SD卡GPS目录下" + folderName
										+ "目录中", Toast.LENGTH_SHORT).show();
						}else{
						Toast.makeText(
								MainActivity.this,
								"开始记录NMEA数据，将存储在SD卡GPS目录下" + folderName
										+ "目录中", Toast.LENGTH_SHORT).show();
						}
						recordNMEA.setChecked(true);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						folderName = null;
						recordNMEA.setChecked(false);
						Toast.makeText(MainActivity.this, "SD卡不存在！无法存储",
								Toast.LENGTH_SHORT).show();
					}
				}
				if (!recordNMEA.isChecked()) {
					folderName = null;
					Toast.makeText(MainActivity.this,
							"停止记录NMEA数据，数据已存储在SD卡GPS文件夹中",
							Toast.LENGTH_SHORT).show();
					recordNMEA.setChecked(false);
				}
			}
		});
	}
    @Override  
    protected void onResume() {  
        super.onResume();  
        Log.e("===", "start onResume~~~");  
        if(satellitesView==null)
		satellitesView = (SatellitesView) findViewById(R.id.satellitesView);

    }  
    @Override  
    protected void onPause() {  
        super.onPause();  
        Log.e("===", "start onPause~~~");
        satellitesView=null;
    } 
	/**
	 * 更新Tab标签的背景图
	 * 
	 * @param tabHost
	 */
	private void updateTabStyle(final TabHost mTabHost) {
		TabWidget tabWidget = mTabHost.getTabWidget();
		for (int i = 0; i < tabWidget.getChildCount(); i++) {
			RelativeLayout tabView = (RelativeLayout) mTabHost.getTabWidget()
					.getChildAt(i);

			TextView text = (TextView) tabWidget.getChildAt(i).findViewById(
					android.R.id.title);
			text.setTextSize(19);
			// 文字居中
			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) text
					.getLayoutParams();
			params.width = RelativeLayout.LayoutParams.MATCH_PARENT;
			params.height = RelativeLayout.LayoutParams.MATCH_PARENT;
			text.setLayoutParams(params);
			text.setGravity(Gravity.CENTER);

			if (mTabHost.getCurrentTab() == i) {
				// 选中
				tabView.setBackgroundResource(R.drawable.bg_tab_selected);
				text.setTextColor(this.getResources().getColorStateList(
						R.color.W));
			} else {
				// 未选中
				tabView.setBackgroundResource(R.drawable.bg_tab_normal);
				text.setTextColor(this.getResources().getColorStateList(
						R.color.dB));
			}
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		// Toast.makeText(MainActivity.this,
		// "。。。"+event.getX(),
		// Toast.LENGTH_SHORT).show();
		final int action = event.getAction();

		switch (action) {
		case MotionEvent.ACTION_DOWN:
			x = event.getX();
			y = event.getY();
			break;
		case MotionEvent.ACTION_MOVE:

			break;
		case MotionEvent.ACTION_UP:
			if (event.getX() - x > 100
					&& (event.getY() - y < 100 && event.getY() - y > -100)) {
				tabHost.setCurrentTab(0);
				// Toast.makeText(MainActivity.this,
				// "右滑",
				// Toast.LENGTH_SHORT).show();
			} else if (x - event.getX() > 100
					&& (event.getY() - y < 100 && event.getY() - y > -100)) {
				tabHost.setCurrentTab(1);
				// Toast.makeText(MainActivity.this,
				// "左滑",
				// Toast.LENGTH_SHORT).show();
			} else

				break;
		case MotionEvent.ACTION_CANCEL:

			break;
		}
		return super.dispatchTouchEvent(event);
	}



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.data_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId())// 得到被点击的item的itemId
		{
		case R.id.action_settings: // 对应的ID就是在add方法中所设定的Id
			final EditText time=new EditText(this);
			new AlertDialog.Builder(this)
			.setTitle("设置数据记录时长/分钟(输入大于1的整数)")
			.setIcon(android.R.drawable.ic_dialog_info)
			.setView(time)
			.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(MainActivity.this,
							"设置定时时长为"+time.getText()+"分钟",
							Toast.LENGTH_SHORT).show();
					Editor editor = sp.edit();
					editor.putInt("RTIME", (Integer.parseInt(""+time.getText())));
					editor.commit();
				}
			}).setNegativeButton("手动停止记录",
			new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(MainActivity.this,
							"不设置定时",
							Toast.LENGTH_SHORT).show();
					Editor editor = sp.edit();
					editor.putInt("RTIME", 0);
					editor.commit();
				}
			}).show();
			break;
		case R.id.action_shuoming: // 对应的ID就是在add方法中所设定的Id
			final TextView about=new TextView(this);
			about.setText("功能：\n1.实时获取位置信息、卫星分布与信号强度、NMEA数据\n2.记录一段时间的运动轨迹，在地图上展示，并记录期间的卫星信号变化情况，绘制每颗卫星的信噪比变化图和信噪比分布曲线");
			new AlertDialog.Builder(this)
			.setTitle("GPS信号测试")
			.setIcon(android.R.drawable.ic_dialog_info)
			.setView(about)
			.setPositiveButton("版本更新",
					new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {  
			            PackageInfo pi=MainActivity.this.getPackageManager().getPackageInfo(MainActivity.this.getPackageName(), 0);  
			            Toast.makeText(MainActivity.this,
								"您的版本为"+pi.versionName+"版",
								Toast.LENGTH_SHORT).show(); 
			            Uri uri =Uri.parse("http://zhushou.360.cn/detail/index/soft_id/919999"); 
			            Intent it = new Intent(Intent.ACTION_VIEW,uri); 
			            startActivity(it);
			            
			        } catch (NameNotFoundException e) {  
			            // TODO Auto-generated catch block  
			            e.printStackTrace();  
			        }  
					
					
				}
			}).setNegativeButton("返回",
			null).show();
//			Intent intent = new Intent(MainActivity.this,
//					LogoActivity.class);
//			 intent.putExtra("kind", "help");
//			startActivity(intent);
			break;
		case R.id.action_out:
			finish();
			break;
		}
		return true;
	}

	@Override
	public void onBackPressed() {
		// 这里处理逻辑代码，大家注意：该方法仅适用于2.0或更新版的sdk
		Intent intent = new Intent();
		intent.setAction("android.intent.action.MAIN");
		intent.addCategory("android.intent.category.HOME");
		startActivity(intent);
		return;
	}
}